const express = require("express");
const router = express.Router();
const assert = require("assert");
const jwt = require('jsonwebtoken');
const User = require('../../moudels/userold');
const config = require('../../config/index');

// 处理GET请求
// 注册用户
router.get('/signup', (req, res) => {
  // 查询数据
  // find() 相当于是 类方法
  User.find().then(data => {
    console.log(data)
  }).catch(err => {
    // let token 

  });
  res.cookie(
    "userInfo",
    JSON.stringify({
      _id: "112233445566778899",
      username: "box"
    }),
    { maxAge: 90000, httpOnly: true }
  );
  res.json({
    methods: "GET",
    url: "/user/info"
  });
});
router.get("/signup2", (req, res) => {

  let userName = req.cookies.userInfo;
  console.log(req.cookies);
  console.log(userName);
  res.json({
    methods: "GET",
    url: "/user/info2"
  });
});

// 处理POST请求
router.post('/signup', (req, res) => {
  console.log(req.body)
  if (!req.body.name || !req.body.password) {
    res.send({
      code: 1001,
      success: false,
      message: '用户名或者密码必填!'
    });
  } else {
    // 增加数据
    // 先new 一个数据对象 使用模型.save（）添加
    // 1.声明 用户数据模型
    let newUser = new User({
      name: req.body.name,
      password: req.body.password
    });
    // 2.save 保存 用户账号到db
    newUser.save(err => {
      if (err) {
        return res.send({
          code: 1002,
          success: false,
          message: "注册失败!"
        });
      }
      console.log('写入成功!!!!')
      res.send({
        code: 1000,
        success: true,
        message: "注册成功!欢迎注册云医疗系统!"
      });
    });
  }
  // res.send({
  //   methods: "POST",
  //   url: "/user/info"
  // });
});
// 用户登录
router.post('/login', (req, res) => {
  User.findOne({
    name: req.body.name
  },(err, user) => {
    if (err) {
      assert.equal(null, err);
    }
    if (user) {
      // 检验密码是否正确
      user.comparePW(req.body.password, (err, isMatch) => {
        if (isMatch && !err) {
          console.log("登录成功");
          let content = {name: user.name}; // 要生成token的主题信息
          let secretOrPrivateKey = config.secret; // 这是加密的key（密钥） 
          let token = jwt.sign(content, secretOrPrivateKey, {
            expiresIn: 60*2, //seconds token过期的时间秒
          });
          user.token = token;
          user.save(function (err) {
            if (err) {
              assert(null, err);
              res.json({
                code: 1005,
                success: false,
                message: "token 保存失败，请联系管理员!",
                name: user.name
              });
            }
          });
          res.cookie(
            "token",
            JSON.stringify({
              token: `Bearer +${user.token}`
            }),
            { maxAge: 60*10, httpOnly: true }
          );

          res.send({
            code: 1000,
            success: true,
            message: "登录成功!欢迎注册云医疗系统!",
            name: user.name,
            token: 'Bearer ' + token
          });
        } else {
          res.send({code: 4000, success: false, message: "认证失败,密码错误!" });
        }
      });
    } else {
      res.json({
        code: 1005,
        success: false,
        message: '认证失败,用户不存在!'
      });
    }
  });
});

router.get("/auth", (req, res) => {
  console.log(req.cookies);
  res.json({
    code: 1008,
    success: true,
    message: "认证成功,GET!"
  });
});

router.post("/auth", (req, res) => {
  console.log(req.cookies);
  let token = req.body.token || req.query.token || req.headers['x-access-token'];
  console.log(token);
  res.json({
    code: 1006,
    success: true,
    message: "认证成功,POST!",
    token: req.cookies.token
  });
});

router.get('/setcookie', (req, res) => {
  res.cookie(
    "userInfo",
    JSON.stringify({
      _id: "112233445566778899",
      username: "box"
    }),
    { maxAge: 90000, httpOnly: true }
  );

  res.send(
    JSON.stringify({
      error: null,
      msg: "设置cookie 成功"
    })
  );
});

router.get('/getcookie', (req, res) => {
  console.log(req.cookies);
  res.send(
    JSON.stringify({
      methods: "GET",
      message: "这是RESTful的GET请求",
      pathname: req.pathname,
      path: req.path
    })
  );
});

module.exports = router;
